//
//  TLRechargeCoinsViewController.m
//  WXReader
//
//  Created by huaya on 2025/3/27.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLRechargeCoinsViewController.h"
#import "TLRechargeGoodsModel.h"
#import "TLRechargeCoinsCollectionViewCell.h"
#import "TL_WebViewViewController.h"

@interface TLRechargeCoinsViewController ()<UITextViewDelegate,UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) UIView *navView;

@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UILabel *navTitleLab;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIView *coinView;
@property (nonatomic, strong) UILabel *coinLab;
@property (nonatomic, strong) UILabel *coinNumLab;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) TLRechargeGoodsModel *selectedModel;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *priceLab;
@property (nonatomic, strong) UIButton *rechargeBtn;

@property (nonatomic, strong) UIView *goodsView;
@end

@implementation TLRechargeCoinsViewController
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        
        // 创建 UICollectionViewFlowLayout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        // 设置两列，行间距和列间距
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        layout.itemSize = CGSizeMake((screenWidth - 17 * 2 - 13) / 2, 120);  // 两列，屏幕两边17，列间距13
        layout.minimumLineSpacing = 15; // 行间距
        layout.minimumInteritemSpacing = 13; // 列间距
        layout.sectionInset = UIEdgeInsetsMake(0, 17, 0, 17); // 左右边距17
        layout.sectionHeadersPinToVisibleBounds = NO;
        // 初始化 UICollectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.bounces = NO;
        _collectionView.scrollEnabled = NO;
        // 注册 NIB 文件
        [_collectionView registerNib:[UINib nibWithNibName:@"TLRechargeCoinsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"TLRechargeCoinsCollectionViewCell"];
        
        // 设置背景色
        _collectionView.backgroundColor = [UIColor whiteColor];
        
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor: [UIColor whiteColor]];
    
    [self setUI];
    
}

- (void)setUI{
    [self.view addSubview:self.navView];
    
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.navView.mas_bottom);
    }];
    [self.scrollView addSubview:self.coinView];
    
    [self.scrollView addSubview:self.goodsView];
    [self.goodsView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.goodsView);
    }];
    
    [self.view addSubview:self.bottomView];
    
    [self getUserData];
    
    [MKApplePayUtils sharedInstance].completeTransactionBlock = ^{
        
        [self refreshData];
    };
}

- (void)getUserData{
    
    if (!TL_UserInfoManager.isLogin) {
        
        return;
    }
    
    MJWeakSelf
    
    [APIManager sendGetRequest:[APIURLManager getUserInfo] parameters:nil model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            NSLog(@"%@",requestModel);
            
            TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];

            NSDictionary *userDataDict = [usermodel mj_keyValues];
            
            [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
            
            TL_UserInfoManager.updateWithDict(requestModel.data[@"userInfo"]);
            
            [self netWork];
            
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg ?: WXLocalizedString(@"请求失败")];
            if (requestModel.code == 302) {
                [TL_UserInfoManager logout];
            }
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
        
    }];
}
- (void)refreshData{
    [APIManager sendGetRequest:[APIURLManager getUserInfo] parameters:nil model:TL_UserInfoModel.class success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            
            TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];

            NSDictionary *userDataDict = [usermodel mj_keyValues];
            
            [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
            
            TL_UserInfoManager.updateWithDict(requestModel.data[@"userInfo"]);
            if (TL_UserInfoManager.userInfo.coinNum) {
                self.coinNumLab.text = [NSString stringWithFormat:@"%@",TL_UserInfoManager.userInfo.coinNum];
            }else{
                self.coinNumLab.text = @"0";
            }
            
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg ?: WXLocalizedString(@"请求失败")];
            if (requestModel.code == 302) {
                [TL_UserInfoManager logout];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}
- (void)setupUITwo{
    UIView *payTypeView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.goodsView.frame)+20, kScreenWidth, 100)];
    [payTypeView setBackgroundColor:[UIColor whiteColor]];
    [self.scrollView addSubview:payTypeView];
    
    UILabel *payTypeLab = [[UILabel alloc] initWithFrame:CGRectMake(17, 13, kScreenWidth, 23)];
    payTypeLab.text = @"Payment method";
    payTypeLab.font = MK_FONT_PFSC_Medium(16);
    payTypeLab.textColor = [UIColor blackColor];
    [payTypeView addSubview:payTypeLab];
    
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"apple pay"]];
    imgView.frame = CGRectMake(17, CGRectGetMaxY(payTypeLab.frame)+28, 35, 15);
    [payTypeView addSubview:imgView];
    
    UILabel *appPayLab = [[UILabel alloc] initWithFrame:CGRectMake(10+CGRectGetMaxX(imgView.frame), 0, kScreenWidth, 23)];
    appPayLab.text = @"Apple Pay";
    appPayLab.center = CGPointMake(appPayLab.center.x, imgView.center.y);
    appPayLab.font = [UIFont systemFontOfSize:15];
    appPayLab.textColor = [UIColor blackColor];
    [payTypeView addSubview:appPayLab];
    
    UIButton *payBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-16-18, 0, 18, 18)];
    [payBtn setImage:[UIImage imageNamed:@"hy_xz"] forState:UIControlStateNormal];
    payBtn.center = CGPointMake(payBtn.center.x, imgView.center.y);
    [payTypeView addSubview:payBtn];
    
    UIView *tipsView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(payTypeView.frame)+20, kScreenWidth, 300)];
    [tipsView setBackgroundColor:[UIColor whiteColor]];
    [self.scrollView addSubview:tipsView];
    
    UILabel* titleLab = [[UILabel alloc] initWithFrame:CGRectMake(17, 13, 300, 25)];
    titleLab.text = @"Tips";
    titleLab.textColor = [UIColor colorWithHexString:@"#333333"];
    titleLab.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    [tipsView addSubview:titleLab];
    
    NSString *originalText = @"1. The recharge exchange ratio is 1USD = 100 coins;\n\n2. After recharge and purchase, the system will default to you having agreed to the《User Agreement》and《Privacy Agreement》;\n\nAfter the purchase, if the account balance has not changed for a long time, please submit the question to the customer service in the【Feedback】";

    // 创建可变的富文本
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:originalText];

    // 全局基础样式（添加行高）
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.minimumLineHeight = 20;   // 行高固定为20
    paragraphStyle.maximumLineHeight = 20;   // 确保行高严格一致
    paragraphStyle.alignment = NSTextAlignmentLeft; // 左对齐
    
    // 全局基础样式
    [attributedString addAttributes:@{
        NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#B0B0B0"],
        NSFontAttributeName: [UIFont systemFontOfSize:14],
        NSParagraphStyleAttributeName: paragraphStyle // 应用段落样式
    } range:NSMakeRange(0, originalText.length)];

    // 定义需要高亮的关键词和颜色
    NSDictionary *highlightWords = @{
        @"《User Agreement》": @"user://agreement",
        @"《Privacy Agreement》": @"user://privacy",
        @"【Feedback】": @"user://feedback"
    };

    // 遍历关键词添加高亮样式
    [highlightWords enumerateKeysAndObjectsUsingBlock:^(NSString *word, NSString *link, BOOL *stop) {
        NSRange range = [originalText rangeOfString:word];
        if (range.location != NSNotFound) {
            // 设置颜色
            [attributedString addAttribute:NSForegroundColorAttributeName
                                     value:[UIColor hex_9E6DFC]
                                     range:range];
            // 添加自定义链接（用于点击识别）
            [attributedString addAttribute:NSLinkAttributeName
                                     value:link
                                     range:range];
        }
    }];
    
    // 将 UILabel 替换为 UITextView（支持点击交互）
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(17, CGRectGetMaxY(titleLab.frame)+20, kScreenWidth-17*2, tipsView.frame.size.height-CGRectGetMaxY(titleLab.frame)-20)];
    textView.attributedText = attributedString;
    textView.editable = NO;
    textView.scrollEnabled = NO;
    textView.delegate = self; // 设置代理
    textView.linkTextAttributes = @{}; // 清除默认链接样式
    
    [tipsView addSubview:textView];
    
    [self.scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(tipsView.frame)+100)];
    
    if (TL_UserInfoManager.userInfo.coinNum) {
        
        self.coinNumLab.text = [NSString stringWithFormat:@"%@",TL_UserInfoManager.userInfo.coinNum];
    }else{
        
        self.coinNumLab.text = @"0";
    }
    
    
}

// 实现 UITextViewDelegate 点击事件
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
    if ([URL.scheme isEqualToString:@"user"]) {
        NSString *action = URL.host;
        if ([action isEqualToString:@"agreement"]) {
            // 处理用户协议点击
            TL_WebViewViewController *vc = [[TL_WebViewViewController alloc] init];
            vc.isPresentState = NO;
            vc.navTitle = WXLocalizedString(@"用户协议");
            vc.URLString = [NSString stringWithFormat:@"%@",[APIURLManager AgreementURL]];
            [self.navigationController pushViewController:vc animated:YES];
        } else if ([action isEqualToString:@"privacy"]) {
            // 处理隐私协议点击
            
            TL_WebViewViewController *vc = [[TL_WebViewViewController alloc] init];
            vc.isPresentState = NO;
            vc.navTitle = WXLocalizedString(@"隐私政策");
            vc.URLString = [NSString stringWithFormat:@"%@",[APIURLManager PrivacyURL]];
            [self.navigationController pushViewController:vc animated:YES];
            
        } else if ([action isEqualToString:@"feedback"]) {
            // 处理反馈点击
            NSLog(@"feedback");
        }
        return NO; // 阻止系统处理链接
    }
    return YES;
}
- (UIView *)coinView{
    if (!_coinView) {
        _coinView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 70)];
        [_coinView setBackgroundColor:[UIColor whiteColor]];
        _coinLab = [[UILabel alloc] initWithFrame:CGRectMake(15, (70-20)/2, 50, 20)];
        _coinLab.font = MK_FONT_PFSC_Medium(16);
        _coinLab.textColor = [UIColor colorWithHexString:@"#666666"];
        _coinLab.text = @"Coins:";
        [_coinView addSubview:_coinLab];
        
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"coinsIcon"]];
        imgView.frame = CGRectMake(CGRectGetMaxX(_coinLab.frame)+10, 0, 20, 20);
        imgView.center = CGPointMake(imgView.center.x, _coinLab.center.y);
        [_coinView addSubview:imgView];
        
        _coinNumLab = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imgView.frame)+10, (70-20)/2, 200, 20)];
        _coinNumLab.font = MK_FONT_PFSC_Medium(16);
        _coinNumLab.textColor = [UIColor colorWithHexString:@"#666666"];
        _coinNumLab.text = @"0";
        _coinNumLab.textAlignment = NSTextAlignmentLeft;
        [_coinView addSubview:_coinNumLab];
        
        
        
        
        
    }
    return _coinView;
}
- (void)backAction{
    if (self.navigationController) {
        // 如果导航控制器本身是被 present 的，则 dismiss 整个导航控制器
        if (self.navigationController.presentingViewController) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        // 否则，执行 pop
        else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    // 没有导航控制器，直接 dismiss
    else if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _scrollView.delegate = self;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.bounces = NO;  // 关闭所有方向的弹性效果
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _scrollView.decelerationRate = UIScrollViewDecelerationRateFast; // 快速停止，减少滑动惯性
        [_scrollView setBackgroundColor:[UIColor colorWithHexString:@"#F9F9F9"]];
        [_scrollView setContentSize:CGSizeMake(0, SCREEN_HEIGHT*2)];
    }
    return _scrollView;
}
- (UIView *)navView{
    if (!_navView) {
        _navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, PUB_NAVBAR_HEIGHT)];
        [_navView setBackgroundColor:[UIColor whiteColor]];
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(6, PUB_NAVBAR_HEIGHT - 28 - 6, 28, 28)];
        [_backBtn setImage:[UIImage imageNamed:@"tzxqy_fh"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navView addSubview:_backBtn];
        
        _navTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, PUB_NAVBAR_HEIGHT - 28 - 6, kScreenWidth, 28)];
        _navTitleLab.text = @"Recharge";
        _navTitleLab.textColor = [UIColor colorWithHexString:@"#000000"];
        _navTitleLab.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];
        _navTitleLab.textAlignment = NSTextAlignmentCenter;
        [_navView addSubview:_navTitleLab];
        
        _navView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        _navTitleLab.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
    }
    return _navView;
}
- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-46-MK_SCREEN_SAVE_BOTTOM_HEIGHT, kScreenHeight, 46+MK_SCREEN_SAVE_BOTTOM_HEIGHT)];
        [_bottomView setBackgroundColor:[UIColor whiteColor]];
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
        [lineView setBackgroundColor:[UIColor colorWithHexString:@"#F1F1F1"]];
        [_bottomView addSubview:lineView];
        
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(17, 13, 50, 22)];
        titleLab.text = @"Total:";
        titleLab.textColor = [UIColor colorWithHexString:@"#333333"];
        titleLab.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        [_bottomView addSubview:titleLab];
        [titleLab sizeToFit];
        
        UILabel *priceLab = [[UILabel alloc] initWithFrame:CGRectMake(10+CGRectGetMaxX(titleLab.frame), 13, 50, 22)];
        priceLab.text = @"$ 0";
        priceLab.textColor = [UIColor colorWithHexString:@"#9E6DFC"];
        priceLab.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
        [_bottomView addSubview:priceLab];
        [priceLab sizeToFit];
        self.priceLab = priceLab;
        
        UIButton *rechargeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-124, 0, 124, 46)];
//        [rechargeBtn setBackgroundColor:[UIColor colorGradientChangeWithSize:rechargeBtn.bounds.size direction:LLGradientChangeDirectionLevel startColor:[UIColor colorWithHexString:@"#FEB92F"] endColor:[UIColor colorWithHexString:@"#FFD63E"]]];
        [rechargeBtn setBackgroundColor:[UIColor hex_9E6DFC]];
        [rechargeBtn setTitle:@"Recharge" forState:UIControlStateNormal];
        [rechargeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        rechargeBtn.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
        [rechargeBtn addTarget:self action:@selector(rechargeAction) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:rechargeBtn];
        
    }
    return _bottomView;
}
- (UIView *)goodsView{
    if (!_goodsView) {
        _goodsView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.coinView.frame)+20, kScreenWidth, 300)];
        [_goodsView setBackgroundColor:[UIColor blueColor]];
    }
    return _goodsView;
}


- (void)rechargeAction{
    
    [[MKApplePayUtils sharedInstance] createOrderWithItem:self.selectedModel novelId:nil videoId:nil andIsAuto:NO];
    
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TLRechargeCoinsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TLRechargeCoinsCollectionViewCell" forIndexPath:indexPath];
    
    if (self.dataArr.count>indexPath.row) {
        cell.model = self.dataArr[indexPath.row];
    }
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TLRechargeGoodsModel *model = self.dataArr[indexPath.row];
    
    if (!self.selectedModel) {
        
        model.tl_isSelected = YES;
        self.selectedModel = model;
        
    }else if(self.selectedModel != model){
        
        self.selectedModel.tl_isSelected = NO;
        model.tl_isSelected = YES;
        self.selectedModel = model;
        
    }else if(self.selectedModel == model){
        
        model.tl_isSelected = YES;
        self.selectedModel = model;
        
    }
    
    self.priceLab.text = [NSString stringWithFormat:@"$ %@",self.selectedModel.price];
    
    [self.priceLab sizeToFit];
    
    [_collectionView reloadData];
}
- (void)netWork{
    MJWeakSelf
    [APIManager sendGetRequest:[APIURLManager getOsGoodsList] parameters:@{@"isVip":@"0"} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            
            NSArray *data = [TLRechargeGoodsModel mj_objectArrayWithKeyValuesArray:requestModel.data];
            
            [self.dataArr addObjectsFromArray:data];
            
            int x = (int)data.count / 2;
            int y = (int)data.count % 2;
            
            self.goodsView.frame = CGRectMake(0, CGRectGetMaxY(self.coinView.frame)+20, kScreenWidth, 140*(x+y));
            
            [self setupUITwo];
            
            [weakSelf.collectionView reloadData];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

@end
